<?php
error_reporting(0);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_model.message.message_explain");
//http公共入口
class http_import extends message_queue
{
    public $str_cp_id = null;
    /**
     *  参数
     * @var unknown
     */
	public $mixed_params = null;
	
	/**
	 * 注入消息队列模板
	 * @var unknown
	 */
	public $arr_in_message = array(
                              'base_info'=>array(
                                      'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
                                      'nns_message_id'=>'',  //上游消息ID
                                      'nns_cp_id'=>'', //上游CP标示
                                      'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
                                      'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
                                      'nns_action'=>'', //操作 行为
                                      'nns_type'=>'', //消息 类型
                                      'nns_name'=>'',  //消息名称
                                      'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
                                      'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
                                      'nns_encrypt'=>'', //广州电信悦ME 加密串
                                      'nns_content_number'=>'', //xml文件中包含的内容数量
                              ), //基本信息（存储于nns_mgtvbk_message表中）
                     );
	
	/**
	 * 初始化
	 */
	public function __construct()
	{
	    $arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
	    $this->str_cp_id = array_pop($arr_dir);
	    //加载 xml转为数组的np库
	    \ns_core\m_load::load_np("np_xml_to_array.class.php");
	    //初始化obj DC
	    m_config::get_dc();
	    //接收日志处理
	    m_config::base_write_log('message','request',"-----------消息接收开始-----------",m_config::return_child_path(__FILE__));
	    $data = $_POST;
	    m_config::base_write_log('message','request',"接收POST消息：". var_export($data, true),m_config::return_child_path(__FILE__));
	    if(empty($data))
	    {
	        $data = file_get_contents('php://input');
	        m_config::base_write_log('message','request',"接收流文件消息：". var_export($data, true),m_config::return_child_path(__FILE__));
	        if (is_object(simplexml_load_string($data)))
	        {
	            $data = array(
	                'cmspost' => $data
	            );
	        }
	    }
	    //传入的值有可能是http的query格式的值，并且进行了URLEDcode加密
		if(!is_array($data))
		{
			$data = $this->_deal_import_data($data);
		}
		$this->mixed_params = $data;
	}

	/**
	 * 特殊处理传入的值
	 * @author  <feijian.gao@starcor.cn>
	 * @date	2017年5月22日17:38:03
	 *
	 * @param  array  $data  	参数值
	 * @return array  $arr_tmp  处理之后返回参数
	 */
	public function _deal_import_data($data)
	{
		$arr_tmp = array();
		$data = urldecode($data);
		parse_str($data,$arr_tmp);
		return $arr_tmp;
	}
	
	public function mu_array_change_key_case($array=null)
	{
	    if(!is_array($array) || empty($array))
	    {
	        return $array;
	    }
	    $array = array_change_key_case($array);
	    foreach ($array as $key=>&$val)
	    {
	        if(is_array($val) && !empty($val))
	        {
	            $array[$key] = $this->mu_array_change_key_case($val);
	        }
	    }
	    return $array;
	}
	
	/**
	 * 注入
	 * @return multitype:number |string
	 */
	public function import()
	{
	    $time_rand = microtime(true)*10000;
	    //原始数据存储的字段
	    $this->arr_in_message['base_info']['nns_message_xml'] = is_array($this->mixed_params) ? json_encode($this->mixed_params,JSON_UNESCAPED_UNICODE) : $this->mixed_params;
		$this->arr_in_message['base_info']['nns_cp_id'] = $this->str_cp_id;
		$this->arr_in_message['base_info']['nns_type'] = '3';
		$this->arr_in_message['base_info']['nns_message_time'] = $time_rand;
	    $this->arr_in_message['base_info']['nns_message_content'] = $this->mixed_params['cmspost'];
		//cmspost xml数据
		$xml_data = $this->mixed_params['cmspost'];
		$xml_data = m_config::trim_xml_header($xml_data);
	    if(!m_config::is_xml($xml_data))
	    {
            m_config::base_write_log('message','request',"cmspost参数传入的内容非xml，执行错误",m_config::return_child_path(__FILE__));
	        return $this->bulid_result('400','content is not xml');
	    }
		$dom = new DOMDocument('1.0', 'utf-8');
		$xml_data = "<adi>$xml_data</adi>";
		$dom->loadXML($xml_data);
		$cmspost = $dom->saveXML();
		$xml_arr_data = np_xml_to_array::parse2($cmspost);
		$xml_arr_data = $this->mu_array_change_key_case($xml_arr_data);
		if(!is_array($xml_arr_data) || empty($xml_arr_data))
		{
		    m_config::base_write_log('message','request',"xml_arr_data非数组，执行错误",m_config::return_child_path(__FILE__));
	        return $this->bulid_result('404','content is not array');
		}
		foreach ($xml_arr_data as $key=>$val)
		{
		    if(isset($val['@attributes']['responseurl']) && strlen($val['@attributes']['responseurl']) >0 && strlen($this->arr_in_message['base_info']['nns_encrypt']) <1)
		    {
		        $this->arr_in_message['base_info']['nns_encrypt'] = $val['@attributes']['responseurl'];
		    }
		    if(!isset($val['@attributes']['assetid']) || strlen($val['@attributes']['assetid']) <1)
		    {
	            $this->arr_in_message['base_info']['nns_action'] = '1';
		        $this->arr_in_message['base_info']['nns_message_state'] = '101';
		        $this->arr_in_message['base_info']['nns_message_id'] = '|' .$time_rand.rand(100,999).rand(100,999).rand(100,999);
		        $result = $this->push($this->arr_in_message);
		        m_config::base_write_log('message','request',"assetid is not find，执行错误",m_config::return_child_path(__FILE__));
		        return $this->bulid_result('409','assetid is not find');
		    }
            $this->arr_in_message['base_info']['nns_message_id'] = $val['@attributes']['assetid'] . '|' .$time_rand.rand(100,999).rand(100,999).rand(100,999) ;
		    switch ($key)
		    {
		        //内容传输（添加、取消、删除）
		        case 'transfercontent':
		            $this->arr_in_message['base_info']['nns_action'] = '1';
		            break;
		        case 'canceltransfer':
		            $this->arr_in_message['base_info']['nns_action'] = '9';
		            break;
		        case 'deletecontent':
		            $this->arr_in_message['base_info']['nns_action'] = '3';
		            break;
                //频道（启动、停止）
	            case 'startchannel':
	                $this->arr_in_message['base_info']['nns_action'] = '1';
		            $this->arr_in_message['base_info']['nns_type'] = '6';
	                break;
	            case 'stopchannel':
	                $this->arr_in_message['base_info']['nns_action'] = '3';
		            $this->arr_in_message['base_info']['nns_type'] = '6';
	                break;
		        //获取状态    
		        case 'gettransferstatus':
		            $this->arr_in_message['base_info']['nns_action'] = '99';
		            break;
		        case 'exposecontent':
		            $this->arr_in_message['base_info']['nns_action'] = '99';
		            break;
		        case 'getcontentchecksum':
		            $this->arr_in_message['base_info']['nns_action'] = '99';
		            break;
		        case 'getcontentinfo':
		            $this->arr_in_message['base_info']['nns_action'] = '99';
		            break;
		        case 'getvolumeinfo':
		            $this->arr_in_message['base_info']['nns_action'] = '99';
		            break;
		        default:
		            $this->arr_in_message['base_info']['nns_action'] = '100';
                	$this->arr_in_message['base_info']['nns_message_state'] = '101';
            	    $result = $this->push($this->arr_in_message);
	                return $this->bulid_result('500','content match error');
		    }
		    break;
		}
		if(in_array($key, array('gettransferstatus','exposecontent','getcontentchecksum','getcontentinfo','getvolumeinfo')))
		{
		    return $this->query_queue_info($key, $val);
		}
    	$this->arr_in_message['base_info']['nns_message_state'] = '0';
	    $this->arr_in_message['base_info']['nns_content_number'] = (isset($xml_arr_data[$key]['input']) && is_array($xml_arr_data[$key]['input']) && !empty($xml_arr_data[$key]['input'])) ? count($xml_arr_data[$key]['input']) : 1;
	    //消息队列入库方法
	    $result = $this->push($this->arr_in_message);
        return $this->bulid_result('200','Ok');
	}
	
	
	public function query_queue_info($key,$val)
	{
	    \ns_core\m_load::load_old("nn_logic/c2_task/c2_task.class.php");
	    if($key == 'getcontentinfo' || $key == 'gettransferstatus')
	    {
	        $vod_media = $this->query_vod_media_info($val);
	        if($vod_media['ret'] != 0)
	        {
	            $this->arr_in_message['base_info']['nns_message_state'] = '100';
	            //消息队列入库方法
	            $result = $this->push($this->arr_in_message);
	            return $this->bulid_result('500','content vod match error');
	        }
	        if(isset($vod_media['data_info']) && strlen($vod_media['data_info']) >0)
	        {
	            $this->arr_in_message['base_info']['nns_message_state'] = '99';
	            //消息队列入库方法
	            $result = $this->push($this->arr_in_message);
	            return $this->bulid_result('200','vod ok',$vod_media['data_info'],true);
	        }
	        $vod_media = $this->query_live_media_info($val);
	        if($vod_media['ret'] != 0)
	        {
	            $this->arr_in_message['base_info']['nns_message_state'] = '100';
	            //消息队列入库方法
	            $result = $this->push($this->arr_in_message);
	            return $this->bulid_result('500','content live match error');
	        }
	        if(isset($vod_media['data_info']) && strlen($vod_media['data_info']) >0)
	        {
	            $this->arr_in_message['base_info']['nns_message_state'] = '99';
	            //消息队列入库方法
	            $result = $this->push($this->arr_in_message);
	            return $this->bulid_result('200','live ok',$vod_media['data_info'],true);
	        }
	        $this->arr_in_message['base_info']['nns_message_state'] = '100';
	        //消息队列入库方法
	        $result = $this->push($this->arr_in_message);
	        return $this->bulid_result('404','media not find');
	    }
	}
	
	/**
	 * 点播片源查询
	 * @param unknown $val
	 */
	public function query_vod_media_info($val)
	{
	    \ns_core\m_load::load_old("nn_logic/vod_media/vod_media.class.php");
// 	    $data_media = nl_vod_media_v2::query_by_sql(m_config::get_dc(), "select * from nns_vod_media where nns_import_id like '{$val['@attributes']['assetid']}|%' and nns_cp_id='".$this->str_cp_id."'");
	    $data_media = nl_vod_media_v2::query_by_sql(m_config::get_dc(), "select * from nns_vod_media where nns_import_id = '{$val['@attributes']['assetid']}' and nns_cp_id='".$this->str_cp_id."'");
	    if($data_media['ret'] !=0)
	    {
	        return m_config::return_data(1,'media query error');
	    }
	    if(!isset($data_media['data_info']) || empty($data_media['data_info']) || !is_array($data_media['data_info']))
	    {
	        return m_config::return_data(0,'empty data');
	    }
	    $arr_media_info = null;
	    foreach ($data_media['data_info'] as $arr_media_data_info)
	    {
	        $arr_media_info[$arr_media_data_info['nns_id']] = $arr_media_data_info;
	    }
	    #TODO
	    $result_c2_info = nl_c2_task::query_by_condition_v2(m_config::get_dc(), array('nns_org_id'=>'starcor','nns_type'=>'media','nns_ref_id'=>array_keys($arr_media_info)));
	    if($result_c2_info['ret'] !=0)
	    {
	        return m_config::return_data(1,'queue query error');
	    }
	    $result_c2_info['data_info'] = (isset($result_c2_info['data_info']) && is_array($result_c2_info['data_info']) && !empty($result_c2_info['data_info'])) ? $result_c2_info['data_info'] : null;
	    $temp_c2_info = null;
	    if(is_array($result_c2_info['data_info']) && !empty($result_c2_info['data_info']))
	    {
	        foreach ($result_c2_info['data_info'] as $c2_info)
	        {
	            $temp_c2_info[$c2_info['nns_ref_id']] = $c2_info;
	        }
	    }
	    foreach ($arr_media_info as $value)
	    {
	        $nns_ext_info = (isset($value['nns_ext_info']) && strlen($value['nns_ext_info'])) ? json_decode($value['nns_ext_info'],true) : null;
	        $nns_ext_url = (isset($value['nns_ext_url']) && strlen($value['nns_ext_url'])) ? json_decode($value['nns_ext_url'],true) : null;
	        $str_providerID = isset($nns_ext_url['providerID']) ? $nns_ext_url['providerID'] : '';
	        $str_percentComplete = (isset($temp_c2_info[$value['nns_id']]['nns_status']) && $temp_c2_info[$value['nns_id']]['nns_status'] == '0') ? 100 : 60;
	        if($value['nns_deleted'] == '1')
	        {
	            $str_state = $str_percentComplete == 100 ? 'Canceled' : 'Transfer';
	        }
	        else
	        {
	            $str_state = $str_percentComplete == 100 ? 'Complete' : 'Transfer';
	        }
	        $int_contentSize = (isset($nns_ext_info['size']) && (int)$nns_ext_info['size'] >0) ? (int)$nns_ext_info['size'] : 0;
	        $str_md5Checksum = isset($nns_ext_info['file_md5']) ? $nns_ext_info['file_md5'] : '';
	        $str_playUrl = isset($nns_ext_info['path']) ? $nns_ext_info['path'] : '';
	        $str_md5DateTime = (isset($temp_c2_info[$value['nns_id']]['nns_modify_time']) && strlen($temp_c2_info[$value['nns_id']]['nns_modify_time']) >0) ? $temp_c2_info[$value['nns_id']]['nns_modify_time'] : date("Y-m-d H:i:s");
	        $int_time = strtotime($str_md5DateTime);
	        $str_md5DateTime = date("Y-m-d",$str_md5DateTime).'T'.date("H:i:s",$str_md5DateTime).'Z';
	        $value['nns_import_id'] = explode('|',$value['nns_import_id']);
	        $xml  = '<?xml version="1.0" encoding="UTF-8"?>';
	        $xml .= '<TransferStatus ';
            $xml .=' providerID="'.$str_providerID.'" ';
	        $xml .=' assetID="'.$value['nns_import_id'][0].'" ';
            $xml .=' volumeName="'.$value['nns_name'].'" ';
            $xml .=' state="'.$str_state.'" ';
            $xml .=' percentComplete="'.$str_percentComplete.'" ';
            $xml .=' contentSize="'.$int_contentSize.'" ';
            $xml .=' md5Checksum="'.$str_md5Checksum.'" ';
            $xml .=' md5DateTime="'.$str_md5DateTime.'" ';
            $xml .=' avgBitRate ="'.$value['nns_kbps'].'" ';
            $xml .=' playUrl="'.$str_playUrl.'" ';
	        $xml .= '/>';
            break;
	    }
	    return m_config::return_data(0,'ok',$xml);
	}
	
	/**
	 * 直播片源查询
	 * @param unknown $val
	 */
	public function query_live_media_info($val)
	{
	    \ns_core\m_load::load_old("nn_logic/live/live_media.class.php");
// 	    $data_media = nl_live_media::query_by_sql(m_config::get_dc(), "select * from nns_live_media where nns_content_id like '{$val['@attributes']['assetid']}|%' and nns_cp_id='".$this->str_cp_id."'");
	    $data_media = nl_live_media::query_by_sql(m_config::get_dc(), "select * from nns_live_media where nns_content_id = '{$val['@attributes']['assetid']}' and nns_cp_id='".$this->str_cp_id."'");
	    if($data_media['ret'] !=0)
	    {
	        return m_config::return_data(1,'query error');
	    }
	    if(!isset($data_media['data_info']) || empty($data_media['data_info']) || !is_array($data_media['data_info']))
	    {
	        return m_config::return_data(0,'empty data');
	    }
	    $arr_media_info = null;
	    foreach ($data_media['data_info'] as $arr_media_data_info)
	    {
	        $arr_media_info[$arr_media_data_info['nns_id']] = $arr_media_data_info;
	    }
	    #TODO
	    $result_c2_info = nl_c2_task::query_by_condition_v2(m_config::get_dc(), array('nns_org_id'=>'starcor','nns_type'=>'live_media','nns_ref_id'=>array_keys($arr_media_info)));
	    if($result_c2_info['ret'] !=0)
	    {
	        return m_config::return_data(1,'queue query error');
	    }
	    $result_c2_info['data_info'] = (isset($result_c2_info['data_info']) && is_array($result_c2_info['data_info']) && !empty($result_c2_info['data_info'])) ? $result_c2_info['data_info'] : null;
	    $temp_c2_info = null;
	    if(is_array($result_c2_info['data_info']) && !empty($result_c2_info['data_info']))
	    {
	        foreach ($result_c2_info['data_info'] as $c2_info)
	        {
	            $temp_c2_info[$c2_info['nns_ref_id']] = $c2_info;
	        }
	    }
	    foreach ($arr_media_info as $value)
	    {
	        $nns_ext_info = (isset($value['nns_ext_info']) && strlen($value['nns_ext_info'])) ? json_decode($value['nns_ext_info'],true) : null;
	        $nns_ext_url = (isset($value['nns_ext_url']) && strlen($value['nns_ext_url'])) ? json_decode($value['nns_ext_url'],true) : null;
	        $str_providerID = isset($nns_ext_url['providerID']) ? $nns_ext_url['providerID'] : '';
	        $str_percentComplete = (isset($temp_c2_info[$value['nns_id']]['nns_status']) && $temp_c2_info[$value['nns_id']]['nns_status'] == '0') ? 100 : 60;
	        if($value['nns_deleted'] == '1')
	        {
	            $str_state = $str_percentComplete == 100 ? 'Canceled' : 'Transfer';
	        }
	        else
	        {
	            $str_state = $str_percentComplete == 100 ? 'Complete' : 'Transfer';
	        }
	        $int_contentSize = (isset($nns_ext_info['size']) && (int)$nns_ext_info['size'] >0) ? (int)$nns_ext_info['size'] : 0;
	        $str_md5Checksum = isset($nns_ext_info['file_md5']) ? $nns_ext_info['file_md5'] : '';
	        $str_playUrl = isset($nns_ext_info['path']) ? $nns_ext_info['path'] : '';
	        $str_md5DateTime = (isset($temp_c2_info[$value['nns_id']]['nns_modify_time']) && strlen($temp_c2_info[$value['nns_id']]['nns_modify_time']) >0) ? $temp_c2_info[$value['nns_id']]['nns_modify_time'] : date("Y-m-d H:i:s");
	        $int_time = strtotime($str_md5DateTime);
	        $str_md5DateTime = date("Y-m-d",$str_md5DateTime).'T'.date("H:i:s",$str_md5DateTime).'Z';
	        $value['nns_content_id'] = explode('|',$value['nns_content_id']);

	        $xml  = '<?xml version="1.0" encoding="UTF-8"?>';
	        $xml .= '<TransferStatus ';
	        $xml .=' providerID="'.$str_providerID.'" ';
            $xml .=' assetID="'.$value['nns_content_id'][0].'" ';
            $xml .=' volumeName="'.$value['name'].'" ';
            $xml .=' state="'.$str_state.'" ';
            $xml .=' percentComplete="'.$str_percentComplete.'" ';
            $xml .=' contentSize="'.$int_contentSize.'" ';
            $xml .=' md5Checksum="'.$str_md5Checksum.'" ';
            $xml .=' md5DateTime="'.$str_md5DateTime.'" ';
            $xml .=' avgBitRate ="'.$value['nns_kbps'].'" ';
            $xml .=' playUrl="'.$str_playUrl.'" ';
	        $xml .= '/>';
            break;
	    }
	    return m_config::return_data(0,'ok',$xml);
	}
	
	
	/**
	 * 组装返回的xml文件 
	 * @param int $http_code http状态码
	 * @param string $resson 原因描述
	 * @param string $data xml格式的字符串
	 * @authorliangpan
	 * @date 2015-12-25
	 */
	public function bulid_result($http_code, $resson, $str_data = null, $is_need_header = FALSE)
	{
		header('HTTP/1.1 ' . $http_code . ' ' . $resson);
		header('Status: ' . $http_code . ' ' . $resson);
		header("Content-Type:text/xml;charset=utf-8");
		$str_data = strlen($str_data) >0  ? $str_data : '';
		$str_data = trim($str_data);
		$str_header = $is_need_header ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
 		$str_header = strpos($str_data,'<?xml') === false ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
		return (strlen($str_data) >0) ? $str_header . $str_data : '';
	}
	/**
	 * 类销毁
	 */
	public function __destruct()
	{
	    m_config::base_write_log('message','request',"-----------消息接收结束-----------",m_config::return_child_path(__FILE__));
	}
}
$http_import = new http_import();
$result_import = $http_import->import();
echo $result_import;